package cn.jiahua.test3;

/**
 *  A 和  B 操作同一个变量   num=0;
 * A是生产者   num+1
 * B是消费者   num-1
 * Synchronzied 实现
 */
public class Test {

    public static void main(String[] args) {
        Data data=new Data();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.increment();
            }
        },"A").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.decrement();
            }
        },"B").start();


        new Thread(()->{
            for (int i=0;i<10;i++){
                data.increment();
            }
        },"C").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                data.decrement();
            }
        },"D").start();

    }

}

class Data{
    private int number=0;

    public synchronized void increment(){

        while(number!=0){
            try {
                //A B
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        System.out.println(Thread.currentThread().getName()+"===》生产者放入数据了"+number);
        this.notifyAll();
    }

    public synchronized void decrement(){
        while(number==0){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        System.out.println(Thread.currentThread().getName()+"===》消费者消费数据"+number);
        this.notifyAll();
    }






}
